// 自定义画笔管理器
export class CustomBrushManager {
    constructor() {
        this.isDrawing = false;
        this.currentPath = [];
        this.paths = []; // 存储所有绘制的路径
        this.brushCanvas = null;
        this.brushContext = null;
        this.brushSize = 3; // 固定为3px
        this.brushColor = '#ff0000'; // 固定为红色
        this.isActive = false;
        this.viewportElement = null;
        this.originalImageData = null;
        this.viewportId = null; // 添加视口ID标识
    }

    // 初始化画笔管理器
    initialize(viewportElement, viewportId = null) {
        this.viewportElement = viewportElement;
        this.viewportId = viewportId;
        this.createBrushCanvas();
        this.addEventListeners();
        console.log(`自定义画笔管理器已初始化 - 视口: ${viewportId || 'unknown'}`);
    }

    // 创建画笔画布
    createBrushCanvas() {
        if (!this.viewportElement) return;

        // 创建覆盖画布
        this.brushCanvas = document.createElement('canvas');
        this.brushCanvas.style.position = 'absolute';
        this.brushCanvas.style.top = '0';
        this.brushCanvas.style.left = '0';
        this.brushCanvas.style.pointerEvents = 'none';
        this.brushCanvas.style.zIndex = '1000';
        this.brushCanvas.id = `customBrushCanvas_${this.viewportId || 'default'}`;

        // 设置画布尺寸
        const rect = this.viewportElement.getBoundingClientRect();
        this.brushCanvas.width = rect.width;
        this.brushCanvas.height = rect.height;

        this.brushContext = this.brushCanvas.getContext('2d');
        this.brushContext.lineCap = 'round';
        this.brushContext.lineJoin = 'round';

        // 将画布添加到视口
        this.viewportElement.appendChild(this.brushCanvas);
    }

    // 添加事件监听器
    addEventListeners() {
        if (!this.brushCanvas) {
            console.warn('画笔canvas不存在，无法添加事件监听器');
            return;
        }

        console.log('添加画笔事件监听器到canvas:', this.brushCanvas);

        // 鼠标按下事件
        this.brushCanvas.addEventListener('mousedown', (e) => {
            console.log('画笔mousedown事件触发, isActive:', this.isActive);
            if (!this.isActive) return;
            this.startDrawing(e);
        });

        // 鼠标移动事件
        this.brushCanvas.addEventListener('mousemove', (e) => {
            if (!this.isActive || !this.isDrawing) return;
            this.draw(e);
        });

        // 鼠标松开事件
        this.brushCanvas.addEventListener('mouseup', (e) => {
            console.log('画笔mouseup事件触发, isActive:', this.isActive);
            if (!this.isActive) return;
            this.stopDrawing(e);
        });

        // 鼠标离开事件
        this.brushCanvas.addEventListener('mouseleave', (e) => {
            if (!this.isActive) return;
            this.stopDrawing(e);
        });

        // 触摸事件支持
        this.brushCanvas.addEventListener('touchstart', (e) => {
            if (!this.isActive) return;
            e.preventDefault();
            const touch = e.touches[0];
            this.startDrawing(touch);
        });

        this.brushCanvas.addEventListener('touchmove', (e) => {
            if (!this.isActive || !this.isDrawing) return;
            e.preventDefault();
            const touch = e.touches[0];
            this.draw(touch);
        });

        this.brushCanvas.addEventListener('touchend', (e) => {
            if (!this.isActive) return;
            e.preventDefault();
            this.stopDrawing(e);
        });
    }

    // 开始绘制
    startDrawing(e) {
        this.isDrawing = true;
        this.currentPath = [];
        
        const rect = this.brushCanvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        this.currentPath.push({ x, y });
        
        this.brushContext.beginPath();
        this.brushContext.moveTo(x, y);
        this.brushContext.strokeStyle = this.brushColor;
        this.brushContext.lineWidth = this.brushSize;
    }

    // 绘制
    draw(e) {
        if (!this.isDrawing) return;
        
        const rect = this.brushCanvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        this.currentPath.push({ x, y });
        
        this.brushContext.lineTo(x, y);
        this.brushContext.stroke();
    }

    // 停止绘制
    stopDrawing(e) {
        if (!this.isDrawing) return;
        
        this.isDrawing = false;
        
        // 保存当前路径
        if (this.currentPath.length > 1) {
            this.paths.push({
                id: Date.now(),
                points: [...this.currentPath],
                color: this.brushColor,
                size: this.brushSize
            });
        }
        
        this.currentPath = [];
        this.brushContext.closePath();
    }

    // 激活画笔工具
    activate() {
        this.isActive = true;
        if (this.brushCanvas) {
            this.brushCanvas.style.pointerEvents = 'auto';
            console.log('画笔已激活，pointerEvents设置为auto');
        } else {
            console.warn('画笔canvas不存在，无法激活');
        }
        console.log('自定义画笔已激活');
    }

    // 停用画笔工具
    deactivate() {
        this.isActive = false;
        this.isDrawing = false;
        if (this.brushCanvas) {
            this.brushCanvas.style.pointerEvents = 'none';
        }
        console.log('自定义画笔已停用');
    }

    // 清除所有绘制
    clearAll() {
        this.paths = [];
        this.currentPath = [];
        this.redraw();
        console.log('已清除所有绘制');
    }

    // 撤销最后一次绘制
    undo() {
        if (this.paths.length > 0) {
            this.paths.pop();
            this.redraw();
            console.log('已撤销最后一次绘制');
        }
    }

    // 重绘所有路径
    redraw() {
        if (!this.brushContext) return;
        
        // 清除画布
        this.brushContext.clearRect(0, 0, this.brushCanvas.width, this.brushCanvas.height);
        
        // 重绘所有路径
        this.paths.forEach(path => {
            this.brushContext.beginPath();
            this.brushContext.strokeStyle = path.color;
            this.brushContext.lineWidth = path.size;
            this.brushContext.lineCap = 'round';
            this.brushContext.lineJoin = 'round';
            
            if (path.points.length > 0) {
                this.brushContext.moveTo(path.points[0].x, path.points[0].y);
                for (let i = 1; i < path.points.length; i++) {
                    this.brushContext.lineTo(path.points[i].x, path.points[i].y);
                }
                this.brushContext.stroke();
            }
        });
    }

    // 获取绘制统计信息
    getStats() {
        return {
            totalPaths: this.paths.length,
            totalPoints: this.paths.reduce((sum, path) => sum + path.points.length, 0)
        };
    }

    // 导出绘制数据
    exportData() {
        return {
            paths: this.paths,
            settings: {
                brushColor: this.brushColor,
                brushSize: this.brushSize
            }
        };
    }

    // 导入绘制数据
    importData(data) {
        if (data.paths) {
            this.paths = data.paths;
        }
        if (data.settings) {
            this.brushColor = data.settings.brushColor || this.brushColor;
            this.brushSize = data.settings.brushSize || this.brushSize;
        }
        this.redraw();
    }

    // 销毁管理器
    destroy() {
        if (this.brushCanvas && this.brushCanvas.parentNode) {
            this.brushCanvas.parentNode.removeChild(this.brushCanvas);
        }
        this.brushCanvas = null;
        this.brushContext = null;
        this.viewportElement = null;
        this.paths = [];
        this.currentPath = [];
        this.isActive = false;
        this.isDrawing = false;
    }

    // 更新画布尺寸
    updateCanvasSize() {
        if (!this.viewportElement || !this.brushCanvas) return;
        
        const rect = this.viewportElement.getBoundingClientRect();
        this.brushCanvas.width = rect.width;
        this.brushCanvas.height = rect.height;
        
        // 重新设置画笔样式
        this.brushContext.lineCap = 'round';
        this.brushContext.lineJoin = 'round';
        
        // 重绘所有路径
        this.redraw();
    }
}

// 多画笔管理器 - 管理多个视口的画笔实例
export class MultiBrushManager {
    constructor() {
        this.brushManagers = new Map(); // 存储每个视口的画笔管理器
        this.activeViewportId = null; // 当前活动的视口ID
        this.isGlobalActive = false; // 全局激活状态
    }

    // 为指定视口初始化画笔
    initializeBrushForViewport(viewportElement, viewportId) {
        // 如果已存在，先销毁
        if (this.brushManagers.has(viewportId)) {
            this.brushManagers.get(viewportId).destroy();
        }

        // 创建新的画笔管理器
        const brushManager = new CustomBrushManager();
        brushManager.initialize(viewportElement, viewportId);
        
        this.brushManagers.set(viewportId, brushManager);
        
        // 如果全局激活状态为true，激活这个视口的画笔
        if (this.isGlobalActive) {
            brushManager.activate();
        }
        
        
        console.log(`为视口 ${viewportId} 初始化画笔管理器`);
        return brushManager;
    }

    // 激活所有视口的画笔
    activate() {
        this.isGlobalActive = true;
        this.brushManagers.forEach((brushManager, viewportId) => {
            brushManager.activate();
        });
        console.log('所有视口的画笔已激活');
    }

    // 停用所有视口的画笔
    deactivate() {
        this.isGlobalActive = false;
        this.brushManagers.forEach((brushManager, viewportId) => {
            brushManager.deactivate();
        });
        console.log('所有视口的画笔已停用');
    }

    // 清除所有视口的绘制
    clearAll() {
        this.brushManagers.forEach((brushManager, viewportId) => {
            brushManager.clearAll();
        });
        console.log('已清除所有视口的绘制');
    }

    // 撤销指定视口的最后一次绘制
    undo(viewportId) {
        const brushManager = this.brushManagers.get(viewportId);
        if (brushManager) {
            brushManager.undo();
        }
    }

    // 撤销所有视口的最后一次绘制
    undoAll() {
        this.brushManagers.forEach((brushManager, viewportId) => {
            brushManager.undo();
        });
    }

    // 获取指定视口的绘制统计
    getStats(viewportId) {
        const brushManager = this.brushManagers.get(viewportId);
        return brushManager ? brushManager.getStats() : null;
    }

    // 获取所有视口的绘制统计
    getAllStats() {
        const stats = {};
        this.brushManagers.forEach((brushManager, viewportId) => {
            stats[viewportId] = brushManager.getStats();
        });
        return stats;
    }

    // 导出指定视口的绘制数据
    exportData(viewportId) {
        const brushManager = this.brushManagers.get(viewportId);
        return brushManager ? brushManager.exportData() : null;
    }

    // 导出所有视口的绘制数据
    exportAllData() {
        const data = {};
        this.brushManagers.forEach((brushManager, viewportId) => {
            data[viewportId] = brushManager.exportData();
        });
        return data;
    }

    // 导入指定视口的绘制数据
    importData(viewportId, data) {
        const brushManager = this.brushManagers.get(viewportId);
        if (brushManager) {
            brushManager.importData(data);
        }
    }

    // 导入所有视口的绘制数据
    importAllData(data) {
        Object.keys(data).forEach(viewportId => {
            this.importData(viewportId, data[viewportId]);
        });
    }

    // 销毁指定视口的画笔管理器
    destroyBrushForViewport(viewportId) {
        const brushManager = this.brushManagers.get(viewportId);
        if (brushManager) {
            brushManager.destroy();
            this.brushManagers.delete(viewportId);
            console.log(`销毁视口 ${viewportId} 的画笔管理器`);
        }
    }

    // 销毁所有画笔管理器
    destroy() {
        this.brushManagers.forEach((brushManager, viewportId) => {
            brushManager.destroy();
        });
        this.brushManagers.clear();
        this.isGlobalActive = false;
        this.activeViewportId = null;
        console.log('已销毁所有画笔管理器');
    }

    // 更新指定视口的画布尺寸
    updateCanvasSize(viewportId) {
        const brushManager = this.brushManagers.get(viewportId);
        if (brushManager) {
            brushManager.updateCanvasSize();
        }
    }

    // 更新所有视口的画布尺寸
    updateAllCanvasSizes() {
        this.brushManagers.forEach((brushManager, viewportId) => {
            brushManager.updateCanvasSize();
        });
    }

    // 获取指定视口的画笔管理器
    getBrushManager(viewportId) {
        return this.brushManagers.get(viewportId);
    }

    // 获取所有画笔管理器
    getAllBrushManagers() {
        return Array.from(this.brushManagers.values());
    }

    // 检查是否有画笔管理器
    hasBrushManagers() {
        return this.brushManagers.size > 0;
    }

    // 获取画笔管理器数量
    getBrushManagerCount() {
        return this.brushManagers.size;
    }
}

// 创建单例实例
const customBrushManager = new CustomBrushManager();
const multiBrushManager = new MultiBrushManager();

export default customBrushManager;
export { multiBrushManager }; 